﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SHRMS.Account
{
    public partial class Form_AppSettings : Form
    {
        private IDbConnection _dbConnection;
        private string SqlServerConnectionString, MySqlConnectionString, SqliteConnectionString, OleDbConnectionString;
        public Form_AppSettings()
        {
            InitializeComponent();
            _dbConnection = new DbFactory().DefaultDbConnection;
            InitalizeConnectionStringInfo();
            LoadServices();
        }

        /// <summary>
        /// 初始化数据库连接信息
        /// </summary>
        private void InitalizeConnectionStringInfo()
        {
            #region 获取App.config数据库连接字符串
            SqlServerConnectionString = ConfigurationManager.AppSettings[DbType.SqlServer.ToString()];
            MySqlConnectionString = ConfigurationManager.AppSettings[DbType.MySql.ToString()];
            SqliteConnectionString = ConfigurationManager.AppSettings[DbType.Sqlite.ToString()];
            OleDbConnectionString = ConfigurationManager.AppSettings[DbType.OleDb.ToString()];
            #endregion
            #region Sql Server
            set_cBox_verification.SelectedIndex = 0;
            var SqlServer_Array = SqlServerConnectionString.Split(';');
            foreach (var item in SqlServer_Array)
            {
                if (item.Contains("Data Source"))
                {
                    Set_Txt_SqlHost.Text = item.Split('=').Last();
                }
                else if (item.Contains("Database"))
                {
                    set_txt_sqldb.Text = item.Split('=').Last();
                }
                else if (item.Contains("User ID"))
                {
                    set_cBox_verification.SelectedIndex = 1;
                    set_txt_SqlUser.Text = item.Split('=').Last();
                }
                else if (item.Contains("password"))
                {
                    Set_Txt_MySqlPwd.Text = item.Split('=').Last();
                }
            }
            #endregion
            #region MySql
            var MySql_Array = MySqlConnectionString.Split(';');
            foreach (var item in MySql_Array)
            {
                if (item.Contains("server"))
                {
                    this.Set_Txt_MysqlHost.Text = item.Split('=').Last();
                }
                else if (item.Contains("port"))
                {
                    Set_Txt_MySqlPort.Text = item.Split('=').Last();
                }
                else if (item.Contains("database"))
                {
                    Set_Txt_MySqlDbName.Text = item.Split('=').Last();
                }
                else if (item.Contains("user"))
                {
                    Set_Txt_MySqlUser.Text = item.Split('=').Last();
                }
                else if (item.Contains("password"))
                {
                    Set_Txt_MySqlPwd.Text = item.Split('=').Last();
                }
            }
            #endregion
            #region Sqlite
            var Sqlite_Array = SqliteConnectionString.Split(';');
            foreach (var item in Sqlite_Array)
            {
                if (item.Contains("Data Source"))
                {
                    Set_Txt_SqliteDB.Text = item.Split('=').Last();
                }
            }
            #endregion
            #region OleDb
            var OleDb_Array = OleDbConnectionString.Split(';');
            foreach (var item in OleDb_Array)
            {
                if (item.Contains("Provider"))
                {
                    Set_OleDb_Provider.Text = item.Split('=').Last();
                }
                else
                {
                    Set_OleDb_DataSoures.Text += item.Replace("Data Source=","");
                }
            }
            #endregion
        }

        /// <summary>
        /// 获取当前正在使用的数据库信息
        /// </summary>
        private void LoadServices()
        {
            //获取数据库类型
            main_cbox_DbType.DataSource = Enum.GetNames(typeof(DbType)).ToList();
            string DefaultDb = ConfigurationManager.AppSettings["DefaultDb"];
            var _dbType = (DbType)Enum.Parse(typeof(DbType), DefaultDb, true);
            main_cbox_DbType.SelectedItem = _dbType.ToString();
            //获取主机信息
            switch (_dbType)
            {
                case DbType.SqlServer:
                    main_lab_ip.Text = Set_Txt_SqlHost.Text;
                    break;
                case DbType.MySql:
                    main_lab_ip.Text = Set_Txt_MysqlHost.Text;
                    break;
                case DbType.Sqlite:
                    main_lab_ip.Text = "Localhost";
                    break;
                case DbType.OleDb:
                    var OleDb_Array = OleDbConnectionString.Split(';');
                    foreach (var item in OleDb_Array)
                    {
                        if (item.ToLower().Contains("data source"))
                        {
                            main_lab_ip.Text = item.Split('=').Last();
                            return;
                        }
                        else if (item.ToLower().Contains("server"))
                        {
                            main_lab_ip.Text = item.Split('=').Last();
                            return;
                        }
                    }
                    break;
                default:
                    break;
            }
            //获取连接状态
            try
            {
                _dbConnection.Open();
                main_lab_statetxt.Text = "已连接";
                _dbConnection.Close();
            }
            catch (Exception ex)
            {
                main_lab_statetxt.Text = "未连接";
                MessageBox.Show(ex.Message,"连接失败",MessageBoxButtons.OK,MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 更新SqlServer连接字符串
        /// </summary>
        private void UpDateSqlServerConnectionString()
        {
            int type = set_cBox_verification.SelectedIndex;
            string SqlServerIp = Set_Txt_SqlHost.Text,
                Database = set_txt_sqldb.Text,
                uid = set_txt_SqlUser.Text,
                pwd = Set_Txt_SqlPwd.Text;
            if (type==1)
            {
                SqlServerConnectionString = $@"Data Source={SqlServerIp};Database={Database};Integrated Security=True;Connect Timeout=30;ApplicationIntent=ReadWrite;";
            }
            else
            {
                SqlServerConnectionString = $@"Data Source={SqlServerIp};Database={Database};User ID={uid};password={pwd};Integrated Security=True;Connect Timeout=30;ApplicationIntent=ReadWrite;";
            }
        }

        /// <summary>
        /// 更新MySql连接字符串
        /// </summary>
        private void UpDateMySqlConnectionString()
        {
            string ip = Set_Txt_MysqlHost.Text,
                 port = Set_Txt_MySqlPort.Text,
                 db = Set_Txt_MySqlDbName.Text,
                 user = Set_Txt_MySqlUser.Text,
                 pwd = Set_Txt_MySqlPwd.Text;
            MySqlConnectionString = $"server={ip};user={user};database={db};port={port};password={pwd};Charset=utf8;";
        }

        /// <summary>
        /// 更新Sqlite连接字符串
        /// </summary>
        private void UpDateSqliteConnectionString()
        {
            SqliteConnectionString = $"Data Source={Set_Txt_SqliteDB.Text};Version=3;UTF8Encoding=True;";
        }

        /// <summary>
        /// 更新OleDb连接字符串
        /// </summary>
        private void UpDateOleDbConnectionString()
        {
            string Provider = Set_OleDb_Provider.Text,
                DataSource = Set_OleDb_DataSoures.Text;
            OleDbConnectionString = $"Provider ={Provider};Data Source={DataSource};";
        }
        private void Btn_MySqlTest_Click(object sender, EventArgs e)
        {
            Db_Test(DbType.MySql);
        }

        private void Btn_MySqlSave_Click(object sender, EventArgs e)
        {
            UpDateAppConfig(DbType.MySql);
        }

        private void Btn_SqliteOpenDoc_Click(object sender, EventArgs e)
        {
            OpenFileDialog fileDialog = new OpenFileDialog();
            fileDialog.Multiselect = false;
            fileDialog.Title = "请选择文件";
            fileDialog.Filter = "所有文件(*sqlite*)|*.db*|*.sqlite*|"; //设置要选择的文件的类型
            if (fileDialog.ShowDialog() == DialogResult.OK)
            {
                string file = fileDialog.FileName;//返回文件的完整路径
                Set_Txt_SqliteDB.Text = file;
            }
        }

        private void Btn_SqliteTest_Click(object sender, EventArgs e)
        {
            Db_Test(DbType.Sqlite);
        }

        private void btn_SqlServerTest_Click(object sender, EventArgs e)
        {
            Db_Test(DbType.SqlServer);
        }

        private void Btn_SqlServerSave_Click(object sender, EventArgs e)
        {
            UpDateAppConfig(DbType.SqlServer);
        }

        private void main_btn_save_Click(object sender, EventArgs e)
        {
            string SqlType = main_cbox_DbType.SelectedItem.ToString();
            var _dbType = (DbType)Enum.Parse(typeof(DbType), SqlType, true);
            UpDateAppConfig(_dbType, true);
            _dbConnection = new DbFactory().DefaultDbConnection;
            LoadServices();
        }

        private void Form_AppSettings_FormClosed(object sender, FormClosedEventArgs e)
        {
            DialogResult = DialogResult.OK;
        }

        private void Btn_OleDbTest_Click(object sender, EventArgs e)
        {
            Db_Test(DbType.OleDb);
        }

        private void Btn_OleDbSave_Click(object sender, EventArgs e)
        {
            UpDateAppConfig(DbType.OleDb);
        }

        private void Btn_SqliteSave_Click(object sender, EventArgs e)
        {
            UpDateAppConfig(DbType.Sqlite);
        }
        /// <summary>
        /// 数据库连接测试
        /// </summary>
        /// <param name="dbType"></param>
        /// <param name="ConnectionString"></param>
        private void Db_Test(DbType dbType)
        {
            string ConnectionString = string.Empty;
            switch (dbType)
            {
                case DbType.SqlServer:
                    UpDateSqlServerConnectionString();
                    ConnectionString = SqlServerConnectionString;
                    break;
                case DbType.MySql:
                    UpDateMySqlConnectionString();
                    ConnectionString = MySqlConnectionString;
                    break;
                case DbType.Sqlite:
                    UpDateSqliteConnectionString();
                    ConnectionString = SqliteConnectionString;
                    break;
                case DbType.OleDb:
                    UpDateOleDbConnectionString();
                    ConnectionString = OleDbConnectionString;
                    break;
                default:
                    break;
            }
            try
            {
                using (var db = new DbFactory().DbConnectionObject(dbType, ConnectionString))
                {
                    db.Open();
                    MessageBox.Show("数据库连接成功！", "连接成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    db.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString(), "连接失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 更新数据库连接字符串至App.config文件
        /// </summary>
        /// <param name="dbType">键名：数据库类型</param>
        /// <param name="UpDateDefaultDb">修改默认数据库选项</param>
        private void UpDateAppConfig(DbType dbType, bool? UpDateDefaultDb = false)
        {
            string keyName = string.Empty,
                KeyValue = string.Empty; ;

            if ((bool)UpDateDefaultDb)
            {
                keyName = "DefaultDb";
                KeyValue = dbType.ToString();
            }
            else
            {
                keyName = dbType.ToString();
                switch (dbType)
                {
                    case DbType.SqlServer:
                        UpDateSqlServerConnectionString();
                        KeyValue = SqlServerConnectionString;
                        break;
                    case DbType.MySql:
                        UpDateMySqlConnectionString();
                        KeyValue = MySqlConnectionString;
                        break;
                    case DbType.Sqlite:
                        UpDateSqliteConnectionString();
                        KeyValue = SqliteConnectionString;
                        break;
                    case DbType.OleDb:
                        UpDateOleDbConnectionString();
                        KeyValue = OleDbConnectionString;
                        break;
                    default:
                        break;
                }
            }

            try
            {
                var result = ConfigurationManager.AppSettings.AllKeys.ToList().IndexOf(keyName);
                //判断配置文件中是否存在键为keyName的项
                if (result >= 0)
                {
                    //存在：修改配置文件中键为keyName的项的值
                    Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                    config.AppSettings.Settings[keyName].Value = KeyValue;
                    config.Save(ConfigurationSaveMode.Modified);
                    ConfigurationManager.RefreshSection("appSettings");
                }
                else
                {
                    //不存在：添加配置文件的项，键为keyName，值为keyValue
                    Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                    config.AppSettings.Settings.Add(keyName, KeyValue);
                    config.Save(ConfigurationSaveMode.Modified);
                    ConfigurationManager.RefreshSection("appSettings");
                }
                MessageBox.Show("保存成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString(), "保存失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}
